package com.guardchina.framework.web.impl;

import com.guardchina.framework.util.exception.login.TokenExpException;
import com.guardchina.framework.web.api.TokenValidator;
import com.guardchina.framework.web.model.UserFeature;
import com.guardchina.framework.web.properties.LoginProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：token强制过期校验器
 *
 * @author lwb
 * @date 2019/11/5 10:04
 */
@Slf4j
public class TokenForceExpValidator implements TokenValidator {

    private static final String ALL_USER = "all";

    private LoginProperties properties;

    public TokenForceExpValidator(LoginProperties jwtProperties){
        this.properties = jwtProperties;
    }

    @Override
    public void verify(UserFeature userFeature) {

        String userKey = userFeature.getUserKey();


        if(!needCheck(userKey, properties)){
            return;
        }

        Long minCreateTime = properties.getMinCreateTime();

        if(minCreateTime != null && userFeature.getCreateTime() < minCreateTime){
            log.debug("用户{}登录时间{}小于{}强制过期", userKey, userFeature.getCreateTime(), minCreateTime);
            throw TokenExpException.error();
        }
    }

    private boolean needCheck(String userKey, LoginProperties properties){
        if(StringUtils.isEmpty(properties.getExpUserKeys())){
            return false;
        }
        if(ALL_USER.equals(properties.getExpUserKeys())){
            return true;
        }
        List<String> userKeys = Arrays.stream(properties.getExpUserKeys().split(",")).collect(Collectors.toList());

        return userKeys.contains(userKey);

    }
}
